package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类
 */
@Slf4j
@Component
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;
    /**
     * 每分钟校验未支付订单 超过15分钟未支付的订单直接取消
     */
    @Scheduled(cron = "0 * * * * *")
    public void closeUnPaidOrder(){
        log.info("定时任务 取消15分钟未支付订单");
        // 查询未支付的 当前时间15分钟之前的订单
        LocalDateTime orderTime = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT,orderTime);

        if (ordersList != null && ordersList.size() > 0) {
            // 如果有未支付的订单 直接取消
            ordersList.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("超时未支付");
                orderMapper.update(order);
            });
        }
    }
}
